<template>
  <div class="audio-management">
    <div class="page-header">
      <h2>音频课程管理</h2>
    </div>

    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :model="searchForm" inline>
        <el-form-item label="音频信息">
          <el-input v-model="searchForm.audioInfo" placeholder="请输入音频信息" clearable />
        </el-form-item>
        <el-form-item label="音频类型">
          <el-select v-model="searchForm.audioType" placeholder="请选择音频类型" clearable>
            <el-option label="英语" :value="1" />
            <el-option label="冥想" :value="2" />
            <el-option label="音乐" :value="3" />
            <el-option label="汉语言" :value="4" />
            <el-option label="故事" :value="5" />
          </el-select>
        </el-form-item>
        <el-form-item label="课程状态">
          <el-select v-model="searchForm.audioState" placeholder="请选择状态" clearable>
            <el-option label="上架" :value="1" />
            <el-option label="下架" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchAudios">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
          <el-button type="primary" @click="showAddDialog = true">
            <el-icon><Plus /></el-icon>
            新增音频课程
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-area">
      <el-table :data="audioList" v-loading="loading" stripe>
        <el-table-column prop="audioId" label="音频ID" width="80" />
        <el-table-column prop="audioInfo" label="音频信息" width="200" />
        <el-table-column prop="audioPrice" label="音频价格" width="120">
          <template #default="{ row }">
            ¥{{ row.audioPrice?.toFixed(2) || '0.00' }}
          </template>
        </el-table-column>
        <el-table-column prop="subscribeNum" label="订单量" width="100" />
        <el-table-column prop="audioType" label="音频类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getAudioTypeTag(row.audioType)">
              {{ getAudioTypeText(row.audioType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="audioState" label="课程状态" width="120">
          <template #default="{ row }">
            <el-tag :type="row.audioState === 1 ? 'success' : 'danger'">
              {{ getAudioStateText(row.audioState) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="editAudio(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button size="small" type="danger" @click="deleteAudio(row.audioId)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="isEdit ? '编辑音频课程' : '新增音频课程'"
      v-model="showAddDialog"
      width="600px"
      @close="resetForm"
    >
      <el-form :model="audioForm" :rules="audioRules" ref="audioFormRef" label-width="100px">
        <el-form-item label="音频信息" prop="audioInfo">
          <el-input v-model="audioForm.audioInfo" placeholder="请输入音频信息" />
        </el-form-item>
        <el-form-item label="音频价格" prop="audioPrice">
          <el-input-number v-model="audioForm.audioPrice" :min="0" :precision="2" placeholder="请输入音频价格" />
        </el-form-item>
        <el-form-item label="订单量" prop="subscribeNum">
          <el-input-number v-model="audioForm.subscribeNum" :min="0" placeholder="请输入订单量" />
        </el-form-item>
        <el-form-item label="音频类型" prop="audioType">
          <el-select v-model="audioForm.audioType" placeholder="请选择音频类型">
            <el-option label="英语" :value="1" />
            <el-option label="冥想" :value="2" />
            <el-option label="音乐" :value="3" />
            <el-option label="汉语言" :value="4" />
            <el-option label="故事" :value="5" />
          </el-select>
        </el-form-item>
        <el-form-item label="课程状态" prop="audioState">
          <el-select v-model="audioForm.audioState" placeholder="请选择状态">
            <el-option label="上架" :value="1" />
            <el-option label="下架" :value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh, Edit, Delete } from '@element-plus/icons-vue'
import { audioApi } from '@/api/audio'

// 响应式数据
const loading = ref(false)
const audioList = ref([])
const showAddDialog = ref(false)
const isEdit = ref(false)
const audioFormRef = ref()

// 搜索表单
const searchForm = reactive({
  audioInfo: '',
  audioType: null,
  audioState: null
})

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 音频表单
const audioForm = reactive({
  audioId: null,
  audioInfo: '',
  audioPrice: 0,
  subscribeNum: 0,
  audioState: 1,
  audioType: null
})

// 表单验证规则
const audioRules = {
  audioInfo: [
    { required: true, message: '请输入音频信息', trigger: 'blur' }
  ],
  audioPrice: [
    { required: true, message: '请输入音频价格', trigger: 'blur' }
  ],
  audioType: [
    { required: true, message: '请选择音频类型', trigger: 'change' }
  ],
  audioState: [
    { required: true, message: '请选择课程状态', trigger: 'change' }
  ]
}

// 获取音频类型文本
const getAudioTypeText = (type) => {
  const typeMap = {
    1: '英语',
    2: '冥想',
    3: '音乐',
    4: '汉语言',
    5: '故事'
  }
  return typeMap[type] || '未知'
}

// 获取音频类型标签类型
const getAudioTypeTag = (type) => {
  const tagMap = {
    1: 'primary',
    2: 'success',
    3: 'warning',
    4: 'info',
    5: 'danger'
  }
  return tagMap[type] || 'info'
}

// 获取课程状态文本
const getAudioStateText = (state) => {
  const stateMap = {
    1: '上架',
    0: '下架'
  }
  return stateMap[state] || '未知'
}

// 搜索音频课程
const searchAudios = async () => {
  loading.value = true
  try {
    const response = await audioApi.getAudioList(searchForm)
    if (response.code === 200) {
      audioList.value = response.data || []
      pagination.total = audioList.value.length
    }
  } catch (error) {
    console.error('搜索音频课程失败:', error)
  } finally {
    loading.value = false
  }
}

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    audioInfo: '',
    audioType: null,
    audioState: null
  })
  searchAudios()
}

// 编辑音频课程
const editAudio = (row) => {
  isEdit.value = true
  Object.assign(audioForm, row)
  showAddDialog.value = true
}

// 删除音频课程
const deleteAudio = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这个音频课程吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await audioApi.deleteAudio(id)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      searchAudios()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除音频课程失败:', error)
    }
  }
}

// 提交表单
const submitForm = async () => {
  try {
    await audioFormRef.value.validate()

    const response = isEdit.value
      ? await audioApi.updateAudio(audioForm)
      : await audioApi.addAudio(audioForm)

    if (response.code === 200) {
      ElMessage.success(isEdit.value ? '修改成功' : '新增成功')
      showAddDialog.value = false
      searchAudios()
    }
  } catch (error) {
    console.error('提交失败:', error)
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(audioForm, {
    audioId: null,
    audioInfo: '',
    audioPrice: 0,
    subscribeNum: 0,
    audioState: 1,
    audioType: null
  })
  isEdit.value = false
  audioFormRef.value?.resetFields()
}

// 分页处理
const handleSizeChange = (val) => {
  pagination.pageSize = val
  searchAudios()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  searchAudios()
}

// 初始化
onMounted(() => {
  searchAudios()
})
</script>

<style scoped>
.audio-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-area {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.table-area {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>